package com.liam.translation;

import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.servlet.DefaultServlet;
import org.eclipse.jetty.servlet.ServletContextHandler;
import org.eclipse.jetty.servlet.ServletHolder;
import org.eclipse.jetty.websocket.jsr356.server.deploy.WebSocketServerContainerInitializer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.websocket.server.ServerContainer;
import java.net.URL;

/**
 * 简单的Web服务器
 * 提供静态资源和WebSocket服务
 * 
 * @author liam
 */
public class WebServer {

    private static final Logger logger = LoggerFactory.getLogger(WebServer.class);
    private static final int PORT = 8080;

    public static void main(String[] args) {
        Server server = new Server(PORT);

        // 创建Servlet上下文
        ServletContextHandler context = new ServletContextHandler(ServletContextHandler.SESSIONS);
        context.setContextPath("/");

        // 设置静态资源目录
        URL resourceDir = WebServer.class.getResource("/static");
        if (resourceDir != null) {
            // 创建默认Servlet来处理静态资源
            ServletHolder defaultServlet = new ServletHolder("default", DefaultServlet.class);
            defaultServlet.setInitParameter("resourceBase", resourceDir.toString());
            defaultServlet.setInitParameter("dirAllowed", "true");
            context.addServlet(defaultServlet, "/");

            // 配置WebSocket
            try {
                ServerContainer wsContainer = WebSocketServerContainerInitializer.configureContext(context);

                // 注册WebSocket端点
                wsContainer.addEndpoint(com.liam.translation.websocket.SpeechWebSocketServer.class);

                // 启动服务器
                server.setHandler(context);
                server.start();

                logger.info("Web服务器已启动，访问地址: http://localhost:{}", PORT);
                logger.info("按Ctrl+C停止服务器");

                // 等待服务器关闭
                server.join();

            } catch (Exception e) {
                logger.error("启动Web服务器失败", e);
                System.exit(1);
            }
        } else {
            logger.error("找不到静态资源目录");
            System.exit(1);
        }
    }
}